// pages/mine/mine.js

const app = getApp()
var mqtt = require('../../utils/mqtt.js');
//一个全局变量...
var client = null;
//一个全局变量...
let socketOpen = false
const ApiRootUrl = 'http://8.136.195.245:8000/';
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    day: 80,
    count: 2,
    ranking: 10,
    integral: 20,
    credit: 750,
    level: 5,

    toast: false,
    warnToast: false,
    hideToast: false,
    hideWarnToast: false,
    warn401Toast: false,
    hide401Toast: false,

    cardNum: 0,
    MyCardPictureList: [{
        fruitPicture: '/image/card1.png'
      },
      {
        fruitPicture: '/image/card2.png'
      },
      {
        fruitPicture: '/image/card3.jpg'
      },
      {
        fruitPicture: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2453398919,3408790812&fm=26&gp=0.jpg'
      },
      {
        fruitPicture: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1070649221,78984387&fm=26&gp=0.jpg'
      },
    ],

    swiperList: [{
      id: 0,
      type: 'image',
      url: '/image/card0.png'
    }],

    scanStr: "",
    androidDialog2_scancharge: false,
    resmsg: "",
    cardUid: "",
    chargeMoney: 0

  },

  onLoad() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    this.getMyCards()
  },


  getUserInfo(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  // 绑定用户
  navigatetoBinduser() {
    // wx.navigateTo({
    //   url: '/pages/home/home',
    // })
    wx.switchTab({
      url: '/pages/home/home'
    })
  },

  // 卡片账单
  navigatetoCardRecord() {
    wx.switchTab({
      url: '/pages/order/order'
    })
  },

  navigatetoMycards() {
    wx.navigateTo({
      url: '/pages/myCards/myCards',
    })
    // wx.switchTab({
    //   url: '/pages/home/home'
    // })
  },

  navigatetoPayrecord() {
    wx.navigateTo({
      url: '/pages/payRecord/payRecord',
    })
  },


  // 扫码充值，扫描获取oled上二维码包含的卡uid和充值金额
  scanChargemoneycode() {
    var that = this
    wx.scanCode({
      success(res) {
        console.log("res.result=", res.result)
        var splitStr = res.result.split("+")
        console.log("cardUid=", splitStr[0])
        console.log("chargeMoney=", splitStr[1])
        console.log("type=", typeof (splitStr[1]))
        that.setData({
          cardUid: splitStr[0],
          chargeMoney: splitStr[1],
          androidDialog2_scancharge: true
        })
      }
    })
  },
  //调用api生成充值记录
  scanChargeMoney: function () {
    let that = this
    console.log("你在进行api请求")
    console.log("userid:", app.globalData.userId)
    console.log("nickname=", app.globalData.userInfo.nickName)
    // console.log("carduid:", that.data.cardUid)
    // console.log("typeOfuserid:", typeof (app.globalData.userId))
    wx.request({
      // url: 'http://8.136.195.245:8000/card/bindUser',
      // url: 'http://localhost:8001/charge/chargeCard',
      url: ApiRootUrl + 'charge/chargeCard',
      data: {
        userId: app.globalData.userId,
        chargeWay: 2,
        cardUid: that.data.cardUid,
        nickname: app.globalData.userInfo.nickName,
        chargeMoney: that.data.chargeMoney
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'chartset': 'utf-8'
      },
      success(res) {
        console.log("获取数据成功", res)
        console.log("code:", res.data.code)
        that.setData({
          msg: res.data.message
        })
        console.log("res.data.message", res.data.message)
        that.connectMqtt_scancharge(res.data.code + "")
        if (res.data.code == 200) {
          that.openToast()
        }
        if (res.data.code == 400) {
          that.openWarnToast()
        }
        if (res.data.code == 401) {
          that.open401Toast()
        }
      }
    })
  },
  closeScancharge: function () {
    this.setData({
      androidDialog2_scancharge: false,
    })
    this.connectMqtt_scancharge(401 + "")

  },
  confirmScancharge: function () {
    console.log("你点击了确定充值按钮")
    this.setData({
      androidDialog2_scancharge: false,
    })
    this.scanChargeMoney()
  },



  //调用接口，线下充值后，返回信息到mqtt说明充值状态，200成功、400失败、401用户未确定充值
  connectMqtt_scancharge: function (code) {
    const options = {
      connectTimeout: 4000, // 超时时间
      clientId: 'wx_' + parseInt(Math.random() * 100 + 800, 10),
      port: 8083, //重点注意这个,坑了我很久,一定是8083不是1883也不是443
      // username: 'xxx',
      // password: 'xxx',
    }

    client = mqtt.connect('wx://8.136.195.245/mqtt', options)
    client.on('reconnect', (error) => {
      console.log('正在重连:', error)
    })

    client.on('error', (error) => {
      console.log('连接失败:', error)
    })

    let that = this;
    client.on('connect', (e) => {
      console.log('成功连接服务器')
    })
    //发布绑定状态到mqtt的topic
    client.publish('fruit', code + "")
    console.log('发布至fruit:' + code + "");
  },
  //成功弹窗
  openToast: function () {
    this.setData({
      toast: true
    });
    setTimeout(() => {
      this.setData({
        hideToast: true
      });
      setTimeout(() => {
        this.setData({
          toast: false,
          hideToast: false,
        });
      }, 300);
    }, 3000);
  },
  //操作失败弹框
  openWarnToast: function () {
    this.setData({
      warnToast: true
    });
    setTimeout(() => {
      this.setData({
        hidewarnToast: true
      });
      setTimeout(() => {
        this.setData({
          warnToast: false,
          hidewarnToast: false,
        });
      }, 300);
    }, 3000);
  },
  //该卡已被绑定的提示弹框
  open401Toast: function () {
    this.setData({
      warn401Toast: true
    });
    setTimeout(() => {
      this.setData({
        hide401Toast: true
      });
      setTimeout(() => {
        this.setData({
          warn401Toast: false,
          hide401Toast: false,
        });
      }, 300);
    }, 3000);
  },

  getMyCards: function () {
    console.log("调用api获取我的所有卡片")
    var that1 = this
    wx.request({
      url: "http://localhost:8001/card/list/" + app.globalData.userId,
      data: {

      },
      header: {
        "Content-Type": "application/json"
      },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log("res=", res)
        console.log("获取卡片函数res.data.data=", res.data.data)
        that1.setData({
          swiperList: res.data.data
        })
        if (that1.data.swiperList == null) {
          that1.setData({
            ['swiperList[' + 0 + '].url']: "/image/card0.png",
          })
        } else {
         
          that1.setData({
            cardNum: that1.data.swiperList.length,
          })
          console.log("cardNum=",that1.data.cardNum)
          for (let i = 0; i < that1.data.swiperList.length; i++) {
            var that2 = that1
            that2.setData({
              // ['sortList[' + 0 + '].hotrange']: 'hot1',
              ['swiperList[' + i + '].url']: that2.data.MyCardPictureList[i].fruitPicture,
            })
          }
        }
        console.log("赋值后swiperList=", that1.data.swiperList)
      },
      fail: function (err) {}, //请求失败
      complete: function () {} //请求完成后执行的函数
    })
  },
})